using System.Data;
using System.Reflection.PortableExecutable;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ExplorerBar;

namespace 表格控件测试
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {


        }




        #region  添加新行
        /// <summary>
        /// 添加新行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_Click(object sender, EventArgs e)  //添加一行数据
        {
            DataGridViewRow row = new DataGridViewRow();
            // 在DataGridView中添加新行
            dataGridView1.Rows.Add(true, 0, 0, 0);


        }

        private void btn_delect_Click(object sender, EventArgs e) //删除一行数据
        {
            // 确保至少有一行被选中
            if (dataGridView1.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    dataGridView1.Rows.Remove(row);
                }
            }

        }
        #endregion

        #region 获得所选行的数据

        //移动到
        private void btn_MoveTo_Click(object sender, EventArgs e)
        {
            GetSelectedRowData();
        }


        
        /// <summary>
        /// 获得所选行的数据。非0行
        /// </summary>

        private void GetSelectedRowData()
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                DataGridViewRow selectedRow = dataGridView1.SelectedRows[0]; //非0行

                // 获取每一列的数据

                string column1Data = selectedRow.Cells["X"].Value.ToString();
                string column2Data = selectedRow.Cells["Y"].Value.ToString();
                string column3Data = selectedRow.Cells["Z"].Value.ToString();

                // 显示数据或进行其他处理

                MessageBox.Show($"Column1: {column1Data}, Column2: {column2Data}, Column3: {column3Data}");

                Text_X.Text = column1Data;
                Text_Y.Text = column2Data;
                Text_Z.Text = column3Data;

            }
            else

            {
                MessageBox.Show("No row selected.");
            }
        }
        #endregion

        #region
        /// <summary>
        /// 获取所有行的数据
        /// </summary>

        private void GetAllRowsData()
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)//读取表格中的的每一个行
            {
                if (row.IsNewRow) //如果是空白格
                {
                    continue;
                }

                //获取每一行的由左往右的每一列的数据
                var column1Value = row.Cells["X"].Value?.ToString();
                var column2Value = row.Cells["Y"].Value?.ToString();
                var column3Value = row.Cells["Z"].Value?.ToString();
                textBox1.Text = textBox1.Text + $"Row {row.Index}: X = {column1Value}, Y = {column2Value}, Z = {column3Value}" + Environment.NewLine;
                //  Console.WriteLine($"Row {row.Index}: Column1 = {column1Value}, Column2 = {column2Value}, Column3 = {column3Value}");
            }

        }


        /// <summary>
        /// 获取某一行的数值,通过行数获得行数的数据
        /// </summary>
        /// <param name="rowIndex"></param>
        private void GetRowData(int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= dataGridView1.Rows.Count)
            {
                MessageBox.Show("Invalid row index.");
                return;
            }

            DataGridViewRow row = dataGridView1.Rows[rowIndex];

            // 跳过新行（如果 AllowUserToAddRows 为 true，则最后一行是新的空白行）
            if (row.IsNewRow)
            {
                MessageBox.Show("This is a new row intended for adding new data.");
                return;
            }

            // 获取每一列的数据

            var column1Value = row.Cells["Column1"].Value?.ToString();
            var column2Value = row.Cells["Column2"].Value?.ToString();
            var column3Value = row.Cells["Column3"].Value?.ToString();

            // 处理数据，例如输出到控制台

            textBox1.Text = $"Row {row.Index}: Column1 = {column1Value}, Column2 = {column2Value}, Column3 = {column3Value}";
            //  Console.WriteLine($"Row {row.Index}: Column1 = {column1Value}, Column2 = {column2Value}, Column3 = {column3Value}");
        }


        #region  更新位置，把外界的值赋值到表格某一行中
        //更新位置
        //1. 直接修改 DataGridView 的单元格值
        //如果你的 DataGridView 没有绑定到数据源，可以直接修改单元格的值：
        private void UpdateCellValue()
        {

            if (dataGridView1.SelectedRows.Count > 0)
            {
                //获取选中的行
                DataGridViewRow selectedRow = dataGridView1.SelectedRows[0];


                //修改行中的每一列的值

                selectedRow.Cells["X"].Value = Text_X.Text;
                selectedRow.Cells["Y"].Value = Text_Y.Text;
                selectedRow.Cells["Z"].Value = Text_Z.Text;
            }
            else
            {
                MessageBox.Show("Invalid row index");
            }
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            UpdateCellValue();
        }
        #endregion


        private void btn_start_Click(object sender, EventArgs e)
        {
            GetAllRowsData();
        }
        int row1 = 0;
        private void btn_next_Click(object sender, EventArgs e)
        {

            // GetRowData(row1);

            row1++;
        }




        //保存为CSV文件
        private void SaveDataGridViewToCSV(string filePath)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    // 写入列标题

                    for (int i = 0; i < dataGridView1.Columns.Count; i++)
                    {
                        sw.Write(dataGridView1.Columns[i].HeaderText);
                        if (i < dataGridView1.Columns.Count - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.WriteLine();

                    // 写入行数据

                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            for (int i = 0; i < dataGridView1.Columns.Count; i++)
                            {
                                sw.Write(row.Cells[i].Value?.ToString());
                                if (i < dataGridView1.Columns.Count - 1)
                                {
                                    sw.Write(",");
                                }
                            }
                            sw.WriteLine();
                        }
                    }
                }
                MessageBox.Show("Data saved successfully.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }

        //用户自己选中保存路径
        //SaveFileDialog 是一个非常方便的类，可以让用户选择保存文件的位置和名称。
        private void btn_saveClick(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
                sfd.FileName = "data.csv";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    SaveDataGridViewToCSV(sfd.FileName);
                }

            }
        }
        private void btn_load_Click(object sender, EventArgs e)
        {

            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    LoadCSVToDataGridView(ofd.FileName);
                }
            }
        }

        private void LoadCSVToDataGridView(string filePath)
        {
            try
            {
                using (StreamReader sr = new StreamReader(filePath))
                {

                    //清空现有数据

                    dataGridView1.Rows.Clear();

                    dataGridView1.ColumnCount = 0;

                    //读取列标题

                    string headline = sr.ReadLine();
                    if (headline != null)
                    {
                        string[] headers = ParseCSVLine(headline);
                        foreach (string header in headers)
                        {
                            dataGridView1.Columns.Add(header, header);
                        }
                    }



                    //读取行标题
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (line != null)
                        {
                            string[] rows = ParseCSVLine(line);
                            dataGridView1.Rows.Add(rows);
                        }
                    }
                    MessageBox.Show("Data loaded successfully.");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }


        }
        private string[] ParseCSVLine(string line)
        {
            List<string> fields = new List<string>();
            bool inQuotes = false;
            string field = "";

            foreach (char c in line)
            {
                if (c == '"')
                {
                    inQuotes = !inQuotes;
                }
                else if (c == ',' && !inQuotes)
                {
                    fields.Add(field);
                    field = "";
                }
                else

                {
                    field += c;
                }
            }
            fields.Add(field);

            return fields.ToArray();
        }

    }
}
#endregion